<template>
  <view class="work-container">
    <!-- 轮播图 -->
    <uni-swiper-dot class="uni-swiper-dot-box" :info="data" :current="current" field="content">
      <swiper class="swiper-box" :current="swiperDotIndex" @change="changeSwiper">
        <swiper-item v-for="(item, index) in data" :key="index">
          <view class="swiper-item" @click="clickBannerItem(item)">
            <image :src="item.image" mode="aspectFill" :draggable="false" />
          </view>
        </swiper-item>
      </swiper>
    </uni-swiper-dot> 

    <!-- 宫格组件 -->
    <!-- <uni-section title="系统管理" type="line"></uni-section> -->
    <view class="grid-body">
      <uni-grid :column="4" :showBorder="false" @change="changeGrid">
        <uni-grid-item index="0">
          <view class="grid-item-box">
            <uni-icons type="person-filled" size="30"></uni-icons>
            <text class="text">打卡记录</text>
          </view>
        </uni-grid-item>
		<uni-grid-item index="1">
		 <view class="grid-item-box">
		   <uni-icons type="person-filled" size="30"></uni-icons>
		   <text class="text">危险化学品目录</text>
		 </view>
		</uni-grid-item>
      </uni-grid>
    </view>
  </view>
</template>

<script>
  import config from '@/config'
  import { getOpenId, getUserByOpenId,ifRegister,WjRegister,saveKaRecord,getXcxConfig,getPicMsgById} from "@/api/common"
  
  const imageUrl = config.imageUrl
  export default {
    data() {
      return {
        current: 0,
        swiperDotIndex: 0,
         data: [{
             image: imageUrl+'/banner001.jpeg'
           },
           {
             image: imageUrl+'/banner002.jpeg'
           },
           {
             image: imageUrl+'/banner003.jpeg'
           }
         ],
      }
    },
    methods: {
      clickBannerItem(item) {
        console.info(item)
      },
      changeSwiper(e) {
        this.current = e.detail.current
      },
      changeGrid(e) {
		let openId = this.$store.getters.openId;
		if (openId == "")
		{
			console.log("未授权，请求授权！");
			this.checkAndRequestAuthorization(); 
		}
		else
		{
			var vnum = e.detail.index
			if(vnum=="0")
			{
			  //跳转到打卡记录页面
			  this.$tab.navigateTo(`/subpackages/clockDoc/index`)
			}
			else if(vnum=="1")
			{
			  getUserByOpenId({"openId":openId}).then(response => {
			  	   console.log(response.data[0]);
				   if(response.data[0].phone=="9")
				   {
				   		console.log("跳转到知识库页面");
				   			//跳转到打卡记录页面
				   		this.$tab.navigateTo(`/subpackages/knowledgeBase/index`);
				   }
				   else
				   {
				   		this.$modal.showToast('无该模块权限，请联系治安科！')
				   }
			   });
			}
			else
			{
			  console.log("----")
			}
		}
      	
	   },
	   
	   // 页面加载时检查授权状态，并自动提示用户授权
	   checkAndRequestAuthorization() {
	     if (this.isAuthorizing) return; // 如果正在请求授权，则不重复请求
	     this.isAuthorizing = true; // 设置为正在请求授权
	     wx.showModal({
	       title: '授权请求',
	       content: '若要使用完整功能，请授权获取您的微信信息。',
	       showCancel: true,
	       confirmText: '授权',
	       success: (res) => {
	         if (res.confirm) {
	           // 用户点击授权，调用获取用户信息的方法
	   		   this.$modal.loading("授权中，请耐心等待...")
	           this.getUserProfile();
	         } else {
	           // 用户拒绝授权
	           console.log('用户拒绝授权');
	   		   this.$modal.msgError("用户拒绝授权");
	   		   this.showExitPrompt();
	         }
	       },
	       fail: (error) => {
	         console.log('弹窗展示失败', error);
	   			this.$modal.msgError("弹窗展示失败");
	       },
	       complete: () => {
	         this.isAuthorizing = false; // 重置授权标志位
	       }
	     });
	   },
	   // 获取用户信息的方法
	   getUserProfile() {
	     uni.getUserProfile({
	       desc: '获取您的昵称和头像',
	       success: res => {
	         console.log("用户昵称：", res.userInfo.nickName);
	         console.log("用户头像：", res.userInfo.avatarUrl);
	   
	         // 获取微信登录凭证 code
	         wx.login({
	           success: (loginRes) => {
	             if (loginRes.code) {
	   			let code=loginRes.code;
	               console.log("登录凭证 code：", code);
	               // 后台可以使用 code 获取 openid 和 session_key
	               this.fetchOpenId(code);
	             } else {
	               console.log("登录失败：" + loginRes.errMsg);
	   				  this.$modal.msgError("微信登录凭证获取失败");
	   				  
	             }
	           }
	         });
	       },
	       fail: err => {
	         console.error("授权失败：", err);
	   			// this.$modal.msgSuccess("微信授权失败，请联系管理员!");
	       }
	     });
	   },
	   
	   // 获取 openId 的方法
	   fetchOpenId(code) {
	   	getOpenId({"code":code}).then(res => {
	   		  this.$modal.closeLoading()
	   	      console.log("获取openId:",res.data);
	   		  this.$modal.msgSuccess("微信授权成功!");
	   		  //获取允许误差范围
	   		  let range = this.$store.getters.range;
	   		  console.log("----允许误差范围："+range);
	   		  if(range == "")
	   		  {
	   		  	  console.log("-----获取允许误差范围！");
	   		  	  this.getRange(res.data);
	   		  }
	   	      //全局存放获取的openId
	   	      this.openId=res.data;//当前页面存放
	   		  this.$store.dispatch('setOpenId', this.openId)//存放全局
	   		  this.checkUserByOpenId(this.openId);
	   	})
	    
	   },
	   //获取允许误差范围（单位米）
	   getRange(openId){
	   	getXcxConfig({"configKey":"XCX_RANGE","openId":openId}).then(res => { 
	   			let data=res.data;
	   			console.log("允许误差范围：",data,"米");
	   			if(data=="-1"){
	   				console.log("未查询到配置信息，默认为100米!");
	   				this.$store.dispatch('setRange', "100")//存放全局
	   			}
	   			else{
	   				this.$store.dispatch('setRange', data)//存放全局
	   			}
	   	})
	   		  
	   },
	   
	   //检查用户是否已注册,已注册获取用户注册信息直接登录
	   checkUserByOpenId(openId){
	   		  ifRegister({"openId":openId}).then(res => { 
	   			let data=res.data;
	   			if(data=="0"){
	   				console.log("用户未注册,跳转到注册页面!");
	   				this.$tab.reLaunch('/subpackages/auth/register');
	   			}
	   			else if(data=="1" || data=="2"){
	   				console.log(data);
	   				this.$tab.reLaunch('/subpackages/notice/notice')
	   			}
	   			else if(data=="3")
	   			{
	   				//获取用户信息
	   				this.$store.dispatch('GetInfo', openId).then(() => {
	   				  console.log("----获取用户信息成功-----");
	   				});
	   			}
	   	})
	   		  
	   },
	   //退出微信小程序
	   exitWX(){
	   		  wx.showToast({
	   		                  title: '授权失败，正在退出...',
	   		                  icon: 'none',
	   		                  duration: 2000,
	   		                  complete: () => {
	   		                    setTimeout(() => {
	   		                      wx.exitMiniProgram();
	   		                    }, 2000); // 延迟退出以便用户看到提示
	   		                  }
	   		                });
	   },
	   // 提示用户确认退出的方法
	       showExitPrompt() {
	           wx.showModal({
	               title: '确认退出',
	               content: '您未授权，将退出小程序。是否确认？',
	               showCancel: true,
	               confirmText: '退出',
	               cancelText: '重新授权',
	               success: (res) => {
	                   if (res.confirm) {
	   							  wx.exitMiniProgram(); // 确认退出   
	                   } else {
	                       // 用户选择重新授权，重新调用授权方法
	                       this.checkAndRequestAuthorization();
	                   }
	               }
	           });
	       },
		   
    }
  }
</script>

<style lang="scss">
  /* #ifndef APP-NVUE */
  page {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    background-color: #fff;
    min-height: 100%;
    height: auto;
  }

  view {
    font-size: 14px;
    line-height: inherit;
  }

  /* #endif */

  .text {
    text-align: center;
    font-size: 26rpx;
    margin-top: 10rpx;
  }

  .grid-item-box {
    flex: 1;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 15px 0;
  }

  .uni-margin-wrap {
    width: 690rpx;
    width: 100%;
    ;
  }

  .swiper {
    height: 300rpx;
  }

  .swiper-box {
    height: 150px;
  }

  .swiper-item {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #fff;
    height: 300rpx;
    line-height: 300rpx;
  }

  @media screen and (min-width: 500px) {
    .uni-swiper-dot-box {
      width: 400px;
      /* #ifndef APP-NVUE */
      margin: 0 auto;
      /* #endif */
      margin-top: 8px;
    }

    .image {
      width: 100%;
    }
  }
</style>
